export function hasVal(obj, val) {
  return Object.values(obj).findIndex((item) => item === val) !== -1;
}

export function getUrlKey(key) {
  const query = window.location.search.substring(1);
  const vars = query.split('&');
  for (let i = 0; i < vars.length; i += 1) {
    const pair = vars[i].split('=');
    if (pair[0] === key) {
      return pair[1];
    }
  }
  return null;
}

export const cookieTool = {
  getCookie(cname) {
    const name = `${cname}=`;
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i += 1) {
      const c = ca[i].trim();
      if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
    }
    return null;
  },
  setCookie(cname, value, { exMinute = null, path = '\\' } = {}) {
    const d = new Date();
    let expires = '';
    if (exMinute !== null) {
      d.setTime(d.getTime() + exMinute * 60000);
      expires = `expires=${d.toUTCString()}`;
    }
    document.cookie = `${cname}=${value}; ${expires}; path=${path}`;
  },
};
export const base64 = {
  encode(str) {
    return window.btoa(str);
  },
  decode(str) {
    return window.atob(str);
  },
};

export function debounce(func, wait = 300) {
  let timeout = null;
  return () => {
    if (typeof func !== 'function') {
      throw Error('can not debounce a not callable func');
    }
    clearTimeout(timeout);
    timeout = setTimeout(func, wait);
  };
}

export const localCache = {
  set: (key, value) => {
    window.localStorage.setItem(key, value);
  },
  get: (key) => window.localStorage.getItem(key),
};
